<template>
  <div class="layout">
    <div class="sendDiv">
      <div style="display: flex; justify-content: space-between; margin-top: 20px">
        <Breadcrumb class="breadcrumb" :crumbs="crumbs"></Breadcrumb>
      </div>
      <div class="nameDiv">
        <span>申报政策：</span>
        <span
          class="policyName"
          @click="$router.push({path: 'policyDetail', query: {id: sendMsg.policyId}})"
        >{{policy.policy.name}}</span>
      </div>
      <div class="underLine"></div>
      <div class="formDiv">
        <el-form ref="form" :model="sendMsg" :rules="rules" label-width="120px" class="form">
          <el-form-item label="申报理由：" prop="reason">
            <el-input
              type="textarea"
              resize="none"
              v-model.trim="sendMsg.reason"
              placeholder="请输入申报理由："
              :autosize="{minRows: 4, maxRows: 4}"
              maxlength="200"
            ></el-input>
          </el-form-item>
          <el-form-item label="上传申报材料：" prop="files">
            <div style="text-align: left">
              <el-button class="uploadBtn" icon="el-icon-upload" @click="selectFile()">上传文件</el-button>
              <div
                style="display: flex; align-items: center"
                v-for="(file, index) in sendMsg.files"
                :key="index"
              >
                <span>{{file.name}}</span>
                <i class="el-icon-close deleteBtn" @click="deleteFile(index)"></i>
              </div>
              <input
                type="file"
                ref="fileInput"
                accept=" .rar, .zip, .doc, .docx, .pdf, .xls, .xlsx, .jpg, .png"
                v-show="false"
                @change="changeFile"
              />
              <div style="color: #999999">文件大小不超过30M，支持扩展名：.rar .zip .doc .docx .pdf .xls .xlsx .jpg .png</div>
            </div>
          </el-form-item>
          <el-form-item label>
            <div style="text-align: center">
              <Buttons :buttons="buttons" @goBack="goBack" @sendPolicy="sendPolicy"></Buttons>
              <!-- <div class="backBtn" @click="goBack()">返回</div>
              <div
                class="sendBtn"
                :style="'color :' + formatBtn(policy.policy).color + '; background-color :' + formatBtn(policy.policy).bgColor"
                @click="sendPolicy"
                v-if="policy.policy.applyStatus != 2"
              >立即申报</div>
              <div
                class="sendBtn"
                :style="'color :' + formatBtn(policy.policy).color + '; background-color :' + formatBtn(policy.policy).bgColor"
                v-if="policy.policy.applyStatus == 2"
              >已申报</div> -->
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <MaskCover :title="'提交中，请稍等...'" v-show="sending"></MaskCover>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import MaskCover from '@/components/maskCover'

import { checkLogin, confirmEnding, formatSendBtn } from '@/utils/util.js'
import apply from '@/formRules/policy/apply.js'
import { getPolicyDetail, sendPolicy } from "@/common/api/policy.js";

export default {
  name: 'policySend',
  components: { Breadcrumb, MaskCover },
  mixins: [apply],
  computed:{
    buttons(){
      let btns = [{ text: "返回", type: "normal", size: "l", method: "goBack" }]
      if(!this.policy.policy.applyStatus != 2){
        btns.push({ text: "立即申报", type: "success", size: "l", method: "sendPolicy" })
      } else {
        btns.push({ text: "已申报", type: "weakSuccess", size: "l", method: "none", disabled:true })
      }
      return btns
    }
  },
  data() {
    return {
      policy: {
        policy: {
          name: '',
        },
      },
      totalSize : 0, //文件总大小
      sending: false,
      crumbs: [
        {
          label: '政策服务',
          value: 'policy',
        },
        {
          label: '政策清单',
          value: 'policyList',
        },
        {
          label: '政策详情',
          value: `policyDetail?id=${this.$route.query.id}`,
        },
        {
          label: '政策申请',
          value: 'policySend',
          choose: true,
        },
      ],
    }
  },
  methods: {
    /**
     * 返回上一页
     */
    goBack: function () {
      let ns = this
      ns.$router.go(-1)
    },
    /**
     * 获取政策信息
     */
    async getPolicy() {
      let ns = this
      ns.sendMsg.policyId = ns.$route.query.id
      let res = await getPolicyDetail(ns.$route.query.id)
      ns.policy = res.data
    },
    /**
     * 选择文件事件
     */
    selectFile: function () {
      let ns = this
      ns.$refs.fileInput.click()
    },
    /**
     * 完成选择文件事件
     */
    changeFile: function (e) {
      let ns = this
      let file = e.target.files[0]
      if (file == undefined) {
        return
      }
				// 检测文件大小是否过大
				this.totalSize += parseInt(file.size) 
				console.log("this.totalSize",this.totalSize)
      if (file.size / 1048576 >= 30 || this.totalSize / 1048576 >= 30) { // 原为最大50M,10-11改为30M
					this.totalSize -= parseInt(file.size) 
          ns.$message.error('文件合计大小不能超过30MB')
        return
      }
      if (
        !confirmEnding(file.name, [
          '.rar',
          '.zip',
          '.doc',
          '.docx',
          '.pdf',
          '.jpg',
          '.xls', 
          '.xlsx', 
          '.png'
        ])
      ) {
        ns.$message.error('文件格式不正确')
        return
      }
      ns.sendMsg.files.push(file)
      this.$refs['form'].validateField('files')
    },
    /**
     * 删除文件
     */
    deleteFile: function (index) {
      let ns = this
      let fileList = []
      for (let i = 0; i < ns.sendMsg.files.length; i++) {
        if (i != index) {
          fileList.push(ns.sendMsg.files[i])
        }else{
						// 把全局的总计大小减去
						this.totalSize -= parseInt(ns.sendMsg.files[i].size) 
					}
      }
      ns.sendMsg.files = fileList
    },
    /**
     * 申报政策
     */
    async sendPolicy() {sendPolicy
      let ok = false
      this.$refs['form'].validate(async valid => {
        if(valid) ok = true;
      })
      if(!ok) return ;
      this.sending = true
      let formData = new FormData()
      for (let i = 0; i < this.sendMsg.files.length; i++) {
        formData.append('files', this.sendMsg.files[i])
      }
      formData.append('policyId', this.sendMsg.policyId)
      formData.append('reason', this.sendMsg.reason)
      let res = await sendPolicy(formData)
      this.sending = false
      if (res.code == 200) {
        this.$message.success('申报成功')
        this.getPolicy()
        this.$router.back()
      } else {
        this.$message.error(res.msg)
      }
    },
    /**
     * 格式化显示按钮颜色
     */
    formatBtn: function (policy) {
      return formatSendBtn(policy)
    },
  },
  mounted() {
  	let ns = this
  	if(checkLogin(ns)) {
  		ns.crumbs[3].value = ns.crumbs[3].value + '?id=' + ns.$route.query.id
  		ns.getPolicy()
  	}
  }
  // activated() {
  //   let ns = this
  //   if (checkLogin(ns)) {
  //     ns.crumbs[3].value = ns.crumbs[3].value + '?id=' + ns.$route.query.id
  //     ns.getPolicy()
  //   }
  // },
}
</script>

<style scoped>
.breadcrumb {
  width: 1000px;
  margin-bottom: 50px;
}

.sendDiv {
  margin: 20px 0;
  width: 1000px;
  margin: 0 auto;
}

.sendDiv .backBtn {
  display: inline-block;
  border: 1px solid #eeeeee;
  white-space: nowrap;
  font-size: 12px;
  /* height: 30px;
		line-height: 30px;
		width: 70px; */
  padding: 0 35px;
  text-align: center;
  /* display: flex;
		align-items: center;
		justify-content: center; */
  border-radius: 5px;
  margin-right: 10px;
}

.sendDiv .backBtn:hover {
  cursor: pointer;
  box-shadow: 0px 0px 5px #eeeeee;
}

.sendDiv .nameDiv {
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 20px;
}

.sendDiv .nameDiv .policyName {
  color: #045db9;
  transition: all 0.2s ease 0s;
}

.sendDiv .nameDiv .policyName:hover {
  cursor: pointer;
  text-decoration: underline;
}

.sendDiv .underLine {
  width: 800px;
  height: 2px;
  background-color: #045db9;
  margin: 0 auto;
}

.sendDiv .formDiv {
  width: 800px;
  margin: 0 auto;
  padding: 30px 0;
}

.sendDiv .formDiv .uploadBtn {
  background-color: #f1f2f4;
  color: #045db9;
  border-width: 0;
}

.sendDiv .formDiv .sendBtn {
  padding: 0 20px;
  background-color: #045db9;
  display: inline-block;
  color: #ffffff;
  border-radius: 5px;
  transition: all 0.2s ease 0s;
  margin-right: 10px;
}

.sendDiv .formDiv .sendBtn:hover {
  box-shadow: 0px 5px 5px #e1e1e1;
  cursor: pointer;
}

.sendDiv .formDiv .deleteBtn {
  font-size: 20px;
  color: #d00000;
  font-weight: bold;
  margin-left: 10px;
}

.sendDiv .formDiv .deleteBtn:hover {
  cursor: pointer;
}

.layout {
  min-height: 100vh;
  position: relative;
  padding-bottom: 150px;
  box-sizing: border-box;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}
</style>
